<template>
    <van-form ref="xklForm">
        <van-cell-group inset v-for="item in formOptions">
            <div class="form-item">
                <component :is="'XklField'" :form="form" :option="item"></component>
            </div>
        </van-cell-group>
        <slot name="__action"></slot>
    </van-form>

</template>
<script setup lang="ts">
import { ref } from "vue";
import { FormOption } from '~/utils/types.h5'
import { upperLeadCase } from "~/utils";
defineOptions({ name: 'XklForm' })
const props = defineProps(['form'])

const { form } = props

const xklForm = ref()

const opts = form.opts

const formKeys = Object.keys(form)

const formOptions: FormOption[] = []
formKeys.map(key => {
    if (!form['get' + upperLeadCase(key)]) {
        return
    }
    const option = form['get' + upperLeadCase(key)]()
    if (!option) {
        console.error(`未找到${key}的可匹配getter`)
        return
    }


    const placeholderPrefix = option.type.includes('select') ? '请选择' : '请输入'
    const placeholder = option.placeholder || `${placeholderPrefix}${option.label}`

    const field = {
        prop: key,
        type: option.type,
        label: option.label,
        placeholder: placeholder,
        rules: option.rules
    }

    if (opts.mode) {
        if (option.mode && option.mode.includes(opts.mode)) {
            formOptions.push(field)
        }
    } else {
        formOptions.push(field)
    }

})

let enableSubmit = true
form.submit = async (callback) => {
    if (!enableSubmit) {
        return
    }
    enableSubmit = false

    xklForm.value.validate().then(() => {
        callback(() => {
            setTimeout(() => {
                enableSubmit = true
            }, 300)
        })
    }).catch(() => {
        enableSubmit = true
    })
}


form.getRef = () => {
    return xklForm.value
}


</script>